﻿using AutoMapper;
using MediatR;
using Microsoft.Data.SqlClient;
using S.Authorization.API.Application.Command.OrganizationCommand;
using S.Authorization.Domain.Model.Organization;
using S.Authorization.Infrastructure;
using S.Authorization.Infrastructure.Interface.SheepFarms;
using Yitter.IdGenerator;

namespace S.Authorization.API.Application.CommandHandlers.OrganizationCommandHandler
{
    public class SheepFromCommandHandler : IRequestHandler<SheepFromCommand, bool>,IRequestHandler<SheepFromDeleteCommand, int>,IRequestHandler<SheepFromUpdateCommand,int>,IRequestHandler<SheepFromDeleteMoreCommand,string>
    {
        private readonly ISheepFarmsRepository sheep;
        private readonly IMapper mapper;
        private readonly DbHelper dbHelper;
        public SheepFromCommandHandler(ISheepFarmsRepository _sheep,IMapper _mapper,DbHelper _dbHelper)
        {
            this.sheep = _sheep;
            this.mapper = _mapper;
            this.dbHelper = _dbHelper;
        }
        /// <summary>
        /// 新增羊场
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(SheepFromCommand request, CancellationToken cancellationToken)
        {
            
            request.SheepFarmSnowFlake=YitIdHelper.NextId().ToString();
            request.CreateTime=DateTime.Now;
            SheepFarmsModel columns = mapper.Map<SheepFarmsModel>(request);
            return await sheep.AddAsync(columns);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(SheepFromDeleteCommand request, CancellationToken cancellationToken)
        {
            string sqls = "SELECT * FROM [dbo].[ColumnManagementModel] WHERE SheepFarmCode=@SheepFarmCode";
            var parameters = new List<SqlParameter>
            {
                    new SqlParameter("@SheepFarmCode", request.SheepFarmsId),
            };
            var result = await dbHelper.GetListDataBySql<SheepFarmsModel>(sqls, parameters.ToArray());
            if(result.Count==0)
            {
                string sql = "DELETE  FROM [dbo].[SheepFarmsModel] WHERE SheepFarmsId=@SheepFarmsId";
                SqlParameter[] value =
                {
                new SqlParameter("@SheepFarmsId",request.SheepFarmsId),
                };
                return await dbHelper.ExecuteNonQuery(sql, value);
            }
            else
            {
                return 0;
            }
            
        }
        /// <summary>
        /// 修改羊场
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(SheepFromUpdateCommand request, CancellationToken cancellationToken)
        {
            string sql = "UPDATE SheepFarmsModel SET SheepFarmsFullName=@SheepFarmsFullName,SheepFarmsName=@SheepFarmsName,SheepFarmsScale=@SheepFarmsScale,Responsible=@Responsible,FullAddress=@FullAddress,Sate=@Sate,UpdateBy=@UpdateBy,UpdateTime=@UpdateTime,DepartMentId=@DepartMentId,IndustryTitle=@IndustryTitle,Area=@Area,City=@City,Province=@Province WHERE SheepFarmsId=@SheepFarmsId";
            SqlParameter[] value =
            {
                new SqlParameter("@SheepFarmsFullName",request.SheepFarmsFullName),
                new SqlParameter("@SheepFarmsName",request.SheepFarmsName),
                new SqlParameter("@SheepFarmsScale",request.SheepFarmsScale),
                new SqlParameter("@Responsible",request.Responsible),
                new SqlParameter("@FullAddress",request.FullAddress),
                new SqlParameter("@Sate",request.Sate),
                new SqlParameter("@UpdateBy",request.UpdateBy),
                new SqlParameter("@UpdateTime",DateTime.Now),
                new SqlParameter("@DepartMentId",request.DepartMentId),
                new SqlParameter("@IndustryTitle",request.IndustryTitle),
                new SqlParameter("@Area",request.Area),
                new SqlParameter("@City",request.City),
                new SqlParameter("@Province",request.Province),
                new SqlParameter("@SheepFarmsId",request.SheepFarmsId)
            };
            return await dbHelper.ExecuteNonQuery(sql, value);
        }
        /// <summary>
        /// 羊场批量删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<string> Handle(SheepFromDeleteMoreCommand request, CancellationToken cancellationToken)
        {
            string[] idArray = request.Ids.Split(',');

            List<ColumnManagementModel> recordsToDelete = new List<ColumnManagementModel>();

            // 检查每个Id对应的集合是否为空
            foreach (string id in idArray)
            {
                // 执行查询操作
                string sql = "SELECT * FROM ColumnManagementModel WHERE SheepFarmCode IN (SELECT value FROM STRING_SPLIT(@Ids, ','))";
                var parameter = new List<SqlParameter>
                {
                    new SqlParameter("@ids", id),
                };
                var result = await dbHelper.GetListDataBySql<ColumnManagementModel>(sql, parameter.ToArray());

                // 判断结果集是否为空
                if (result != null && result.Count() > 0)
                {
                    string write = $"{id}的羊场正在使用";
                    return write;
                }
                else
                {
                    recordsToDelete.AddRange(result);
                }
            }
            // 执行删除操作
            if (recordsToDelete.Count == 0)
            {
                string deleteSql = "DELETE FROM SheepFarmsModel WHERE SheepFarmsId IN (SELECT value FROM STRING_SPLIT(@Ids, ','))";
                var deleteParameter = new List<SqlParameter>
                {
                    new SqlParameter("@Ids", request.Ids),
                };
                var str = await dbHelper.ExecuteNonQuery(deleteSql, deleteParameter.ToArray());
                return str.ToString();
            }
            else
            {
                return "false";
            }
        }
    }
}
